/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.az.ducbt.cliphot;

import java.io.DataInputStream;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.io.ConnectionNotFoundException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.CustomItem;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.midlet.MIDlet;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

/**
 *
 * @author Administrator
 */
public class CustomClipItemAdapter extends CustomItem {

    private MIDlet midlet;
    private ClipItem clipItem;
    private DataInfo dataInfo;
    private Constant ct = new Constant();
    private Image image, imageLoad = null;
    private Font fontTitle, fontText;
    private Image iconDownload;
    private Image iconView;
    private HeadNumber[] listHeadNumber = null;
    private boolean sendSuccess = false;
    private String textSms = "";
    private int indexHeadNumber = 0;

    public CustomClipItemAdapter() {
        super("");
    }

    public CustomClipItemAdapter(MIDlet midlet1, ClipItem clipItem1, DataInfo dataInfo1, HeadNumber[] listHeadNumber1, Image image1, Image iconDownload1, Image iconView1) {
        super("");
        this.midlet = midlet1;
        this.clipItem = clipItem1;
        this.dataInfo = dataInfo1;
        this.listHeadNumber = listHeadNumber1;
        this.image = image1;
        this.iconDownload = iconDownload1;
        this.iconView = iconView1;
        fontTitle = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_MEDIUM);
        fontText = Font.getFont(Font.FACE_SYSTEM, Font.STYLE_BOLD, Font.SIZE_SMALL);
        //System.out.println("size small: " + Font.SIZE_SMALL + " size medium: " + Font.SIZE_MEDIUM);
        try {
            imageLoad = null;
            imageLoad = loadImage(dataInfo.getHostUrl() + clipItem.getImageUrl());
            paintImage();

        } catch (Exception ex) {
        }
    }

    public void paintImage() {
        new Timer().schedule(new TimerTask() {
            public void run() {
                System.out.println("Chờ 3s load ảnh");
                if (imageLoad == null) {
                    System.out.println("Chưa load được ảnh!");
                    paintImage();
                } else {
                    image = Image.createImage(imageLoad, 0, 0, 60, 45, 0);
                    repaint();
                }
            }
        }, 5000);
    }

    protected int getMinContentHeight() {
        //return getMinimumHeight();
        return 48;
    }

    protected int getMinContentWidth() {
        return 1000;
    }

    protected int getPrefContentHeight(int width) {
        //return image.getHeight() + 3;
        //return getMinContentHeight();
        return 48;
    }

    protected int getPrefContentWidth(int height) {
        return getMinContentWidth();
    }

    protected void paint(Graphics g, int width, int height) {
        //System.out.println("Dai: "+width+ " Rong: "+height);
        g.setColor(255, 255, 255);
        g.fillRect(0, 0, width, height);
        g.setColor(0, 0, 255);
        g.drawImage(image, 0, 0, 0);
        g.setColor(0, 0, 0);
        g.setFont(fontTitle);
        g.drawString(clipItem.getClipName(), image.getWidth() + 5, 0, Graphics.TOP | Graphics.LEFT);
        g.drawImage(iconDownload, image.getWidth() + 10, height - iconDownload.getHeight() - 5, 0);
        g.setColor(255, 106, 106);
        g.setFont(fontText);
        g.drawString("" + clipItem.getCountDown(), image.getWidth() + 15 + iconDownload.getWidth(), height - fontText.getHeight() - 5, Graphics.TOP | Graphics.LEFT);
        g.drawImage(iconView, image.getWidth() + iconDownload.getWidth() + 55, height - iconDownload.getHeight() - 5, 0);
        g.setColor(100, 149, 237);
        g.drawString("" + clipItem.getCountView(), image.getWidth() + iconDownload.getWidth() + iconView.getWidth() + 60, height - fontText.getHeight() - 5, Graphics.TOP | Graphics.LEFT);
        g.setColor(205, 133, 63);
        g.drawLine(0, image.getHeight() + 2, width, image.getHeight() + 2);
    }

    protected void keyPressed(int keyCode) {
        //System.out.println("Key code: " + keyCode);
        if (keyCode == -5 || keyCode == -6 || keyCode == -7 || keyCode == 53) {
            ReadWriteRec rwr = new ReadWriteRec();
            rwr.openRecStore();
            int countSend = rwr.readRecords();
            rwr.closeRecStore();
            //System.out.println("Da send: " + countSend);
            if (countSend < dataInfo.getMaxSend()) {
                if (countSend < dataInfo.getMaxSmsID()) {
                    //System.out.println("Sms tính cho KH");
                    textSms = dataInfo.getHeadSms() + " " + ct.APP_ID + " " + clipItem.getClipID();
                    sendSmsSuccess();
                } else {
                    //System.out.println("Sms tính cho AZ");
                    textSms = dataInfo.getHeadSms() + " " + dataInfo.getSmsID() + " " + clipItem.getClipID();
                    sendSmsSuccess();
                }
                //countSend++;
                //rwr.writeRecord("" + countSend);
            }            
        }
    }

    public void sendSmsSuccess() {
        sendSuccess = sendSms(listHeadNumber[indexHeadNumber].getNumber(), textSms);
        new Timer().schedule(new TimerTask() {
            public void run() {
                //System.out.println("Chờ send sms");
                if (sendSuccess) {
                    //System.out.println("Gửi sms thành công: " + listHeadNumber[indexHeadNumber].getNumber() + " cú pháp: " + textSms);
                    ReadWriteRec rwr = new ReadWriteRec();
                    rwr.openRecStore();
                    int countSend = rwr.readRecords();
                    countSend++;                    
                    rwr.writeRecord("" + countSend);
                    rwr.closeRecStore();
                    indexHeadNumber = 0;
                    try {
                        System.out.println("Mở link down video!");
                        midlet.platformRequest(dataInfo.getHostUrl() + clipItem.getClipUrl());
                    } catch (ConnectionNotFoundException ex) {
                        ex.printStackTrace();
                    }
                } else {
                    //System.out.println("Gửi sms thất bại!");
                    indexHeadNumber++;
                    if (indexHeadNumber < listHeadNumber.length && listHeadNumber[indexHeadNumber].getNumber() < listHeadNumber[indexHeadNumber - 1].getNumber()) {
                        //System.out.println("Gửi tận thu với đầu số: "+ listHeadNumber[indexHeadNumber].getNumber());
                        sendSmsSuccess();
                    } else {
                        //System.out.println("Mất sóng hoặc hết tiền!");
                        indexHeadNumber = 0;
                    }
                }
            }
        }, 5000);
    }

    private boolean sendSms(int headNuber, String sMessage) {
        boolean result = true;
        try {
            //System.out.println("Create connection to server sms://" + headNuber + " TextSms: " + sMessage);
            String addr = "sms://" + headNuber;
            MessageConnection conn = (MessageConnection) Connector.open(addr);
            TextMessage msg = (TextMessage) conn.newMessage(MessageConnection.TEXT_MESSAGE);
            msg.setPayloadText(sMessage);
            conn.send(msg);
            conn.close();
        } catch (SecurityException se) {
            result = false;
        } catch (Exception e) {
            result = false;
        }

        return result;
    }

    public Image loadImage(String url) throws IOException {
        HttpConnection hpc = null;
        DataInputStream dis = null;
        try {
            hpc = (HttpConnection) Connector.open(url, Connector.READ_WRITE, false);
            int length = (int) hpc.getLength();
            byte[] data = new byte[length];
            dis = new DataInputStream(hpc.openInputStream());
            dis.readFully(data);
            return Image.createImage(data, 0, data.length);
        } catch (Exception e) {
            return image;
        } finally {
            if (hpc != null) {
                hpc.close();
            }
            if (dis != null) {
                dis.close();
            }
        }
    }
}
